package com.gwd.task.services.impl;

import cn.hutool.core.date.DateUtil;
import com.gwd.task.entity.FilesUploadEntity;
import com.gwd.task.model.FilesUploadDTO;
import com.gwd.task.model.PageUtils;
import com.gwd.task.repository.FilesUploadRepository;
import com.gwd.task.services.FileLookupMarkServer;
import com.gwd.task.services.FilesUploadServer;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhiyongming
 * @date 2021/1/26 10:24
 */
@Service
public class FilesUploadServerImpl implements FilesUploadServer {

    @Resource
    private FilesUploadRepository filesUploadRepository;
    @Resource
    private FileLookupMarkServer fileLookupMarkServer;

    @Override
    public PageUtils findByPage(FilesUploadDTO dto, PageUtils pageUtils, Long userId) {


        List<FilesUploadDTO> list = findByRead(dto.getGroupId(), dto.getType(), dto.getIsLookUp(), userId, pageUtils.getPageNum(), pageUtils.getPageSize());

        Page<FilesUploadEntity> page
                = filesUploadRepository.findAll(Example.of(new FilesUploadEntity(dto)), pageUtils.convert("fuId", "desc"));

        pageUtils.convert(page).setContent(list);

        return pageUtils;
    }

    @Override
    public void save(FilesUploadDTO dto, Long userId) {
        FilesUploadEntity entity = new FilesUploadEntity();
        entity.setExplain(dto.getExplain());
        entity.setFileCode(dto.getFileCode());
        entity.setGroupId(dto.getGroupId());
        entity.setType(dto.getType());
        entity.setUploadUser(userId);
        entity.setUploadTime(DateUtil.formatDateTime(new Date()));

        FilesUploadEntity newEntity = filesUploadRepository.save(entity);
        dto.setFuId(newEntity.getFuId());
        fileLookupMarkServer.save(dto);
    }

    @Override
    public FilesUploadDTO findByFileCode(String fileCode) {
        FilesUploadEntity entity = new FilesUploadEntity();
        entity.setFileCode(fileCode);
        return filesUploadRepository.findOne(Example.of(entity)).map(FilesUploadDTO::new).orElse(null);
    }

    @Override
    public List<FilesUploadDTO> findByRead(Long groupId, Integer fuType, Integer isLookUp, Long userId, Integer pageNum, Integer pageSize) {

        return filesUploadRepository.findByRead(groupId, fuType, isLookUp, userId, pageNum-1, pageSize)
            .stream().map(FilesUploadDTO::new).collect(Collectors.toList());
    }
}

